package sysmiddleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/admin/internal/svc"
	sys "github.com/vueadmin/app/admin/sys"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"github.com/vueadmin/utils/response"
	"strings"
)

type DeleteFieldMiddleware struct {
	svcCtx *svc.ServiceContext
}

func NewDeleteFieldMiddleware(svcCtx *svc.ServiceContext) *DeleteFieldMiddleware {
	return &DeleteFieldMiddleware{
		svcCtx: svcCtx,
	}
}

// 删除数据表字段中间件
func (p DeleteFieldMiddleware) Handle() gin.HandlerFunc {
	return func(c *gin.Context) {
		var data map[string]interface{}
		var menu sys.Menu
		var fields []sys.Field

		if err := utils.BindAndValid(c, &data); err != nil {
			response.Fail(c, err.Error())
			c.Abort()
			return
		}

		p.svcCtx.Db.Model(&sys.Menu{}).Where("menu_id", data["menu_id"]).Find(&menu)

		if sys.System.GetDBTypeByConnect(menu.Connect) != "mysql" {
			return
		}

		p.svcCtx.Db.Where(data).Find(&fields)

		prefix := sys.System.GetPrefix(menu.Connect)

		if menu.PageType == 1 {
			fieldlist := GetTableFields(p.svcCtx, menu.Connect, prefix+menu.Tablename)
			drop := ""
			pk := sys.System.GetPkByTable(p.svcCtx, menu.Connect, prefix+menu.Tablename)
			for _, val := range fields {
				if val.CreateTableField > 0 && val.Field != pk && conv.IsValueInList(val.Field, fieldlist) {
					drop += fmt.Sprintf(" DROP %s ,", val.Field)
				}
			}
			sql := fmt.Sprintf("ALTER TABLE %s%s", prefix+menu.Tablename, strings.TrimRight(drop, ","))
			if err := sys.System.Conn(p.svcCtx, menu.Connect).Exec(sql).Error; err != nil {
				panic(err)
			}
		} else {
			for _, val := range fields {
				if val.Type == 30 {
					var sql = fmt.Sprintf("ALTER TABLE %s DROP %s;", prefix+menu.Tablename, val.Field)
					if err := sys.System.Conn(p.svcCtx, menu.Connect).Exec(sql).Error; err != nil {
						panic(err)
					}
				}
				sys.System.Conn(p.svcCtx, menu.Connect).Table(prefix+menu.Tablename).Where("name = ?", val.Field).Delete(true)
			}
		}
		c.Set("data", data)
		c.Next()
	}
}
